package service

import (
	"os"
	"os/user"
	"path"

	"gopkg.in/ini.v1"
)

type Config struct {
	Theme  string `json:"theme" ini:"theme"`
	Locale string `json:"locale" ini:"locale"`
}

// ConfigService
type ConfigService struct {
	Cfg Config
}

func NewConfigService() *ConfigService {
	var cfg Config
	i, err := ini.LoadSources(ini.LoadOptions{SkipUnrecognizableLines: true}, getConfigFile())
	if err != nil {
		i = ini.Empty()
	}
	if err := i.MapTo(cfg); err != nil {
		return &ConfigService{Cfg: cfg}
	}
	return &ConfigService{Cfg: cfg}
}

func (c *ConfigService) Get() Config {
	return c.Cfg
}

func (c *ConfigService) Set(cfg Config) error {
	i := ini.Empty()
	err := ini.ReflectFrom(i, &cfg)
	if err != nil {
		return err
	}
	c.Cfg = cfg
	return i.SaveTo(getConfigFile())
}

func getConfigFile() string {
	filename := path.Join(".toy-kit", "RobotArm", "conf.ini")
	dir := ""
	if u, err := user.Current(); err == nil {
		dir = u.HomeDir
	}
	confFile := path.Join(dir, filename)
	os.MkdirAll(path.Dir(confFile), os.ModePerm)
	return confFile
}
